import React from 'react';
import { View, ImageBackground, TouchableWithoutFeedback, FlatList, TouchableOpacity } from 'react-native';
import { Flex, Toast } from 'antd-mobile-rn';
import { Navigation } from 'react-native-navigation';
import { connect } from 'react-redux';
import Scene from '../screen/scene';
import { createStyles } from '../../utils/view';
import NormalHeader from '../../components/NormalHeader';
import CText from '../../components/CText';
import Storage from '../../utils/storage';
import actions from '../../controllers/user/actions';
import { getList } from '../../service/market';
import Icon from 'react-native-vector-icons/icomoon';

const status_arr = [{
  id: 0,
  text: '卖出',
}, {
  id: 1,
  text: '买入'
}
];

class Details extends React.Component {

  static navigatorStyle = {
    navBarHidden: true,
    navBarNoBorder: true,
  };

  constructor(props) {
    super(props);
    this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
    this.state = {
      activeStatus: 0,  // 0: 卖出 1: 买入
      page: 1,
      pageSize: 999,
      hasMore: true,
      loading: false,
      list: []
    };
  }

  onNavigatorEvent(event) {
    if (event.type === 'ScreenChangedEvent') {
      if (event.id === 'didAppear') {
        this.init();
      }
    }
  }

  init = () => {
    this.getList({ page: 1, activeStatus: 0 });
  }

  getList = async ({ page, more, activeStatus }) => {
    let sell_user = '';
    let buy_user  = '';
    const token = await Storage.load('token');
    const userinfo = await Storage.load('userinfo', { token });
    const { pageSize, list } = this.state;
    if (token && userinfo) {
      const userid = userinfo.user_id;
      if (activeStatus === 0) {
        sell_user = userid;
      } else {
        buy_user = userid;
      }
      this.setState({
        loading: true,
      });
      const data = await getList({ token, page, pageSize, sell_user, buy_user });
      console.log('getList', data);
      if (data.code === 0) {
        if (more) { // 如果是下拉加载
          let hasMore = (data.data.length === pageSize);
          this.setState({
            list: list.concat(data.data),
            page: page,
            loading: false,
            hasMore,
            activeStatus
          });
        } else {
          this.setState({
            list: data.data,
            page: page,
            loading: false,
            activeStatus
          });
        }
      } else {
        this.setState({ loading: false });
        Toast.fail(data.msg);
        if (data.code === -1) {
          // 用户过期
          this.props.Logout();
        }
      }
    } else {
      Navigation.showModal({
        screen: 'Login',
        title: '登录',
        passProps: {},
        animated: true,
        animationType: 'slide-horizontal',
        navigatorStyle: {},
        navigatorButtons: {},
      });
    }
  }

  changeStatus = (value: any) => {
    this.getList({ page: 1, activeStatus: value });
  }

  listItem = (item) => {
    const { order_num, create_time, title, sell_price, status } = item;
    return (
      <Flex style={styles.item} direction="column" justify="start" align="center">
        <Flex direction="row" justify="between" align="center">
          <CText size="24">订单号：{order_num}</CText>
          <CText size="24">时间：{create_time}</CText>
        </Flex>
        <View style={styles.dash}></View>
        <Flex direction="row" justify="between" align="center" styles={{ marginBottom: 20 }}>
          <Flex justify="center" align="center" style={{ flex: 1 }}><CText size="32">{title}</CText></Flex>
          <Flex justify="center" align="center" style={{ flex: 1 }}><CText size="32">¥{sell_price}</CText></Flex>
        </Flex>
        {
          status === 1 ?
            <TouchableOpacity activeOpacity={0.6} style={styles.btn_zz}><CText color="#fff">转账</CText></TouchableOpacity> :
            <View style={styles.btn_over}><CText>已完成</CText></View>
        }

      </Flex>
    );
  }

  render() {
    const { list, loading } = this.state;
    console.log('data', list);
    return (
      <Scene isLoading={loading}>
        <NormalHeader
          leftContent={<Icon name="my_02" color={'#fff'} style={{ fontSize: 20 }} />}
          onLeftPress={() => { this.props.navigator.pop() }}
        >我的订单</NormalHeader>
        <Flex style={styles.status_box} direction="row" justify="center" align="center" >
          {
            status_arr.map((status, index) => {
              if (this.state.activeStatus === status.id) {
                return (
                  <View style={styles.status_item} key={status.id}>
                    <ImageBackground style={styles.status_bg} source={require('../../assets/img/home/btn_buy.png')} resizeMode="cover">
                      <CText color="#5F4601">{status.text}</CText>
                    </ImageBackground>
                  </View>
                );
              } else {
                return (
                  <TouchableWithoutFeedback key={status.id} onPress={() => this.changeStatus(status.id)}>
                    <View style={styles.status_item}>
                      <CText color="#5F4601">{status.text}</CText>
                    </View>
                  </TouchableWithoutFeedback>
                );
              }
            })
          }
        </Flex>
        <View style={styles.list_box}>
          <FlatList
            data={this.state.list}
            renderItem={({ item }) => this.listItem(item)}
            // onEndReached={this._onEndReached}
            keyExtractor={(item, index) => `${item.id}`}
          />
        </View>
      </Scene>
    );
  }
}

let styles = {
  status_box: {
    height: 88,
    paddingHorizontal: 58,
  },
  status_item: {
    borderWidth: 2,
    borderColor: '#CC9900',
    borderRadius: 28,
    width: 168,
    height: 56,
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 30,
  },
  status_bg: {
    width: 168,
    height: 52,
    justifyContent: 'center',
    alignItems: 'center',
  },
  list_box: {
    paddingHorizontal: 20,
  },
  item: {
    paddingHorizontal: 20,
    paddingVertical: 20,
    marginBottom: 30,
    borderWidth: 1,
    borderColor: '#CC9900',
    borderRadius: 30,
  },
  dash: {
    flex: 1,
    height: 1,
    backgroundColor: '#F8F1A1',
    marginVertical: 20,
  },
  btn_zz: {
    width: 140,
    height: 60,
    borderRadius: 30,
    backgroundColor: '#C9A43C',
    justifyContent: 'center',
    alignItems: 'center',
  },
  btn_over: {
    width: 140,
    height: 60,
    borderRadius: 30,
    backgroundColor: '#ccc',
    justifyContent: 'center',
    alignItems: 'center',
  }
};

styles = createStyles(styles);

export default connect((Store) => {
  return { loading: Store.AuthRenderData.loading, userInfo: Store.UserRenderData };
}, { getUserInfo: actions.GetUserInfo })(Details);